import createClient, {type Middleware} from "openapi-fetch";
import type { paths } from "./schemas/schema";
import useAuthStore from "~/stores/authStore";

const base_url: string = 'https://api.ravonzz174.ru'

const UNPROTECTED_ROUTES = ["/api/v1/login/", "/api/v1/register/"];


const authMiddleware:Middleware = {
    onRequest(req) {
        if (UNPROTECTED_ROUTES.some((pathname) => req.url.startsWith(pathname))) {
            return undefined; // don’t modify request for certain paths
        }
        const authStore = useAuthStore()

        if (authStore.isAuth) {
            const token = authStore.getToken
            req.headers.set('Authorization', `Bearer ${token}`)
        }
        return req
    },

}

const client = createClient<paths>({ baseUrl: base_url });
client.use(authMiddleware);

type TypeUserInfo = paths['/api/v1/user']['get']['responses']['200']['content']['application/json']
type TypeAllToursInfo = paths['/api/v1/tour/']['get']['responses']['200']['content']['application/json']
type TypeTourInfo = paths['/api/v1/tour/{id}']['get']['responses']['200']['content']['application/json']
type TypeAllUserTours = paths['/api/v1/user/tours']['get']['responses']['200']['content']['application/json']
type TypeTourUsers = paths['/api/v1/tour/{id}/users']['get']['responses']['200']['content']['application/json']

const login = async (requestData: any) => {
    const { data, error , response} = await client.POST('/api/v1/login/', {
        body: requestData
    })
    return { data, error, response }
}

const register = async (requestData: any) => {
    const { data, error, response } = await client.POST('/api/v1/register/', {
        body: requestData
    })
    return { data, error, response }
}

const userInfo = async () => {
    const { data, error, response } = await client.GET('/api/v1/user')
    if (response.status === 401) {
        const authStore = useAuthStore()
        authStore.exit()
        navigateTo('/login')
    }
    return { data, error, response }
}

const generateDescription = async (requestData: any) => {
    const { data, error, response } = await client.POST('/api/v1/generate', {
        body: requestData
    })
    if (response.status === 401) {
        const authStore = useAuthStore()
        authStore.exit()
        navigateTo('/login')
    }
    return { data, error, response }
}

const addTour = async (requestData: any) => {
    const { data, error, response } = await client.POST('/api/v1/tour/', {
        body: requestData
    })
    if (response.status === 401) {
        const authStore = useAuthStore()
        authStore.exit()
        navigateTo('/login')
    }
    return { data, error, response }
}

const getTours = async () => {
     let { data, error, response } = await client.GET('/api/v1/tour/')
    if (response.status === 401) {
        const authStore = useAuthStore()
        authStore.exit()
        let { data, error, response } = await client.GET('/api/v1/tour/')
        return { data, error, response }

    }
    return { data, error, response }
}

const getTour = async (id:number) => {
    let { data, error, response } = await client.GET('/api/v1/tour/{id}', {
        params: {
            path: {
                id: id
            }
        }
    })
    if (response.status === 401) {
        const authStore = useAuthStore()
        authStore.exit()
        let { data, error, response } = await client.GET('/api/v1/tour/{id}', {
            params: {
                path: {
                    id: id
                }
            }
        })
        return { data, error, response }
    }
    return { data, error, response }
}


const deleteTour = async (id:number) => {
    let { data, error, response } = await client.DELETE('/api/v1/tour/{id}', {
        params: {
            path: {
                id: id
            }
        }
    })
    if (response.status === 401) {
        const authStore = useAuthStore()
        authStore.exit()
        navigateTo('/login')
    }
    return { data, error, response }
}

const editTour = async (id:number, requestData:any) => {
    let { data, error, response } = await client.PATCH('/api/v1/tour/{id}', {
        body: requestData,
        params: {
            path: {
                id: id
            }
        }
    })
    if (response.status === 401) {
        const authStore = useAuthStore()
        authStore.exit()
        navigateTo('/login')
    }
    return { data, error, response }
}


const bookTour = async (id:number) => {
    let { data, error, response } = await client.POST('/api/v1/tour/{id}/book', {
        params: {
            path: {
                id: id
            }
        }
    })
    if (response.status === 401) {
        const authStore = useAuthStore()
        authStore.exit()
        navigateTo('/login')
    }
    return { data, error, response }
}


const getUserTours = async () => {
    let { data, error, response } = await client.GET('/api/v1/user/tours')
    if (response.status === 401) {
        const authStore = useAuthStore()
        authStore.exit()
        navigateTo('/login')
    }
    return { data, error, response }
}

const removeBookTour = async (id:number) => {
    let { data, error, response } = await client.DELETE('/api/v1/tour/{id}/book', {
        params: {
            path: {
                id: id
            }
        }
    })
    if (response.status === 401) {
        const authStore = useAuthStore()
        authStore.exit()
        navigateTo('/login')
    }
    return { data, error, response }
}

const getTourUsers = async (id:number) => {
    let { data, error, response } = await client.GET('/api/v1/tour/{id}/users', {
        params: {
            path: {
                id: id
            }
        }
    })
    if (response.status === 401) {
        const authStore = useAuthStore()
        authStore.exit()
        navigateTo('/login')
    }
    return { data, error, response }
}



export default { login, register, userInfo, generateDescription, addTour, getTours, getTour, deleteTour, editTour, bookTour, getUserTours, removeBookTour, getTourUsers}
export type { TypeUserInfo, TypeAllToursInfo, TypeTourInfo, TypeAllUserTours, TypeTourUsers }